import {ref, onMounted} from 'vue'
import source_to_subjects, {old_to_new} from "@/hock/public/source_to_subjects";
import * as api_module from "@/api/api";
import {ElMessage} from "element-plus";

export default function comm_chapter(api_name, params) {
    const source = ref(null)
    const subjects = ref(null)
    const leads = ref({})

    const get_chapter_source = async () => {
        if(api_name == 'collectTopic'){
            let resp = await api_module[api_name](params)//请求数据
            resp.data.answerLogs = [];
            let data = {answerTypes:[{'answerLogs':[resp.data]}]}
            console.log(data)
            source.value = data//保存源数据
            const subjects_leads = source_to_subjects(data);
            console.log('subjects_leads',subjects_leads)
            subjects.value = subjects_leads.subjects
            leads.value = subjects_leads.leads
        }else if(api_name == 'collectTopics'){
            let resp = await api_module[api_name](params).catch(err =>{
                ElMessage({type:'error',message:err.message})
            })//请求数据
            source.value = resp.data//保存源数据
            for (let item of resp.data.answerTypes){
                for (let children in item['answerLogs']){
                    item['answerLogs'][children]['id'] = Number(item['answerLogs'][children]['sort'] + children)
                }
            }
            console.log('源数据',resp.data);
            //source_to_subjects函数返回一个对象 里面包含了subjects和leads
            const subjects_leads = source_to_subjects(resp.data);
            console.log('转换后数据',subjects_leads);
            subjects.value = subjects_leads.subjects
            leads.value = subjects_leads.leads
        }else{
            let resp = await api_module[api_name](params).catch(err =>{
                ElMessage({type:'error',message:err.message})
            })//请求数据
            source.value = resp.data//保存源数据
            console.log('源数据',resp.data);


            console.log('resp.data',resp.data);
            //source_to_subjects函数返回一个对象 里面包含了subjects和leads
            const subjects_leads = source_to_subjects(resp.data);
            console.log('转换后数据',subjects_leads);
            subjects.value = subjects_leads.subjects
            leads.value = subjects_leads.leads
        }
    }
    onMounted(get_chapter_source)
    return {
        source,
        subjects,
        leads,
    }
}
